package com.doublethread.easymart.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * Base64转MultipartFile工具类
 */
public class Base64MultipartFile implements MultipartFile {

    private final byte[] content;
    private final String contentType;
    private final String filename;

    /**
     * 构造方法
     */
    public Base64MultipartFile(byte[] content, String contentType) {
        this.content = content;
        this.contentType = contentType;
        this.filename = generateFilename(contentType);
    }

    /**
     * 从Base64字符串创建MultipartFile
     */
    public static MultipartFile fromBase64(String base64Data) {
        if (base64Data == null || !base64Data.contains(",")) {
            throw new IllegalArgumentException("Invalid base64 format");
        }

        String[] parts = base64Data.split(",");
        if (parts.length != 2) {
            throw new IllegalArgumentException("Invalid base64 format");
        }

        String mimeType = "image/jpeg";
        if (parts[0].contains(":") && parts[0].contains(";")) {
            mimeType = parts[0].split(";")[0].split(":")[1];
        }

        byte[] imageBytes;
        try {
            imageBytes = java.util.Base64.getDecoder().decode(parts[1]);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Invalid base64 data", e);
        }

        return new Base64MultipartFile(imageBytes, mimeType);
    }

    /**
     * 根据内容类型生成文件名
     */
    private String generateFilename(String contentType) {
        String extension = "jpg";
        if (contentType != null) {
            if (contentType.contains("png")) {
                extension = "png";
            } else if (contentType.contains("gif")) {
                extension = "gif";
            } else if (contentType.contains("webp")) {
                extension = "webp";
            }
        }
        return UUID.randomUUID().toString() + "." + extension;
    }

    @Override
    public String getName() {
        return "file";
    }

    @Override
    public String getOriginalFilename() {
        return filename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return content == null || content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(content);
        }
    }
}
